<template>
  <div class="wang-editor">
    <!-- 工具栏 -->
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />

    <!-- 编辑器 -->
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script lang="ts" setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, shallowRef, computed, watch, nextTick } from 'vue'
import type { IToolbarConfig, IEditorConfig } from '@wangeditor/editor'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

const props = withDefaults(
  defineProps<{
    modelValue?: string
    toolbarConfig?: Partial<IToolbarConfig> // 工具栏配置
    editorConfig?: Partial<IEditorConfig> // 编辑器的配置
    disabled: boolean // 是否禁用
  }>(),
  {
    editorConfig: () => ({
      placeholder: '请输入内容'
    })
  }
)

const emit = defineEmits(['update:modelValue'])

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 编辑器模式
const mode = 'default' // 或 'simple'
// 内容 HTML
const valueHtml = computed({
  get() {
    return props.modelValue
  },

  set(value) {
    emit('update:modelValue', value)
  }
})

/**
 * 监听 disabled 来处理是否禁用
 */
watch(
  () => props.disabled,
  (newVal) => {
    nextTick(() => {
      if (newVal) {
        // 禁用
        editorRef.value.disable()
      } else {
        // 不禁用
        editorRef.value.enable()
      }
    })
  },
  {
    immediate: true
  }
)

/**
 * Editor onCreated 事件处理函数
 * @param editor 编辑器实例
 */
function handleCreated(editor: any) {
  editorRef.value = editor

  // setTimeout(() => {
  //   editorRef.value.disable() // 禁用编辑器
  // }, 2000)
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
</script>

<style>
.wang-editor {
  border: 1px solid #ccc;
}

/* .wang-editor *,
.wang-editor *::before,
.wang-editor *::after {
  font-weight: normal;
} */

.wang-editor strong * {
  font-weight: bold !important;
}
</style>
